#include "func.h"

int main(int argc, char *argv[])
{
	if (argc == 1)
	{
		usage(argv[0]);
		return EXIT_ERR;
	}
	
	int c;
	int digit_optind = 0;
	int bShowLineNum = 0;	// show line number or not
	int nSpecifiedLine = -1;// show specified line
	int bBlink = 0;
	char *color = NULL;
	while(1)
	{
		int this_option_optind = optind ? optind : 1;
		
		c = getopt(argc, argv, "bvhlr:c:");
		int len = 0;

		if (c == -1)
			break;
		switch(c)
		{
		case 'b':
			bBlink = 1;
			break;
		case 'v':
			version();
			return EXIT_OK;
		case 'h':
			help();
			return EXIT_OK;
		case 'l':
			bShowLineNum = 1;
			break;
		case 'r':
			nSpecifiedLine = atoi(optarg) - 1;
			break;
		case 'c':
			len = strlen(optarg) + 1;
			color = (char *)malloc(len);
			memset(color, 0, len);
			strncpy(color, optarg, len - 1);
			break;
		case '?':
			break;
		default:
			printf("?? getopt returned\n");
		}
	}


	int nLine = -1;
	if (optind < argc)
	{
		nLine = count_line(argv[optind]);
	}

	if (nLine < 0)
		return EXIT_ERR;	

	if (nLine == 0)
	{
		printf("empty file\n");
		return EXIT_ERR;	
	}

	// show random line
	if (nSpecifiedLine == -1)
	{
		srand(time(NULL));	
		int nLineToShow = rand() % nLine;

		show_line(nLineToShow, color, bBlink, bShowLineNum, argv[optind]);
	}
	else
	{
		show_line(nSpecifiedLine, color, bBlink, bShowLineNum, argv[optind]);
	}

	free(color);

	return EXIT_OK;
}

